home *** CD-ROM | disk | FTP | other *** search
- // This file was created from MWTESample.c, a source file from the
- // "MW TESample" folder, which can be found within the "MacOS Examples"
- // folder distributed with Metrowerks CodeWarrior 8.
- //
- // When compiling/linking this program you must use the library file
- // DataInit.lib from in the "MW TESample" folder.
- //
- // The purpose of this example program is to illustrate the basics
- // programming steps needed to create a client application that
- // utilizes the PPCBrowser and Apple events to communicate with a
- // server application.
- //
- // It is NOT the purpose of this example program to illustrate the
- // correct way to display text in a window or refresh a window that
- // is no longer obscured by another.
- //
- // This program was quickly put together, and it shows.
- //
- // Scott Mulligan - Apple Computer, Inc. - April, 1996
- //
- #include <types.h>
- #include <quickdraw.h>
- #include <fonts.h>
- #include <events.h>
- #include <controls.h>
- #include <windows.h>
- #include <menus.h>
- #include <textedit.h>
- #include <dialogs.h>
- #include <desk.h>
- #include <scrap.h>
- #include <toolutils.h>
- //MW must add LowMem for certain functions (see notes).
- #include <LowMem.h>
- #include <memory.h>
- #include <segload.h>
- #include <files.h>
- #include <osutils.h>
- #include <osevents.h>
- #include <diskinit.h>
- #include <packages.h>
- #include <traps.h>
- //MW added assembler header (to allow inline assembly)
- #include <Assembler.h>
-
- #include <PPCToolbox.h>
- #include <EPPC.h>
- #include <AppleEvents.h>
-
- #include "Symbiont.h"
- #include "version.h"
- #include "Javelin.h"
- #include "JavelinEvents.h"
-
- typedef struct {
- WindowRecord docWindow;
- TEHandle docTE;
- TargetID TheTarget;
- ProcPtr docClik;
- } DocumentRecord, *DocumentPeek;
-
-
- /* The "g" prefix is used to emphasize that a variable is global. */
-
- /* GMac is used to hold the result of a SysEnvirons call. This makes
- it convenient for any routine to check the environment. It is
- global information, anyway. */
- SysEnvRec gMac; /* set up by Initialize */
-
- /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
- trap is available. If it is false, we know that we must call GetNextEvent. */
- Boolean gHasWaitNextEvent; /* set up by Initialize */
-
- /* GInBackground is maintained by our OSEvent handling routines. Any part of
- the program can check it to find out if it is currently in the background. */
- Boolean gInBackground; /* maintained by Initialize and DoEvent */
-
- /* GNumDocuments is used to keep track of how many open documents there are
- at any time. It is maintained by the routines that open and close documents. */
- short gNumDocuments; /* maintained by Initialize, DoNew, and DoCloseWindow */
-
- // Symbiont globals
- long time_of_last_recv=0;
- long time_of_last_send=0;
- long time_of_last_check=0;
- int missed_heartbeats=0;
- Boolean TimeToQuit=false;
- TargetID TheTarget;
- char *ServerOSVer="0.0 ";
-
-
- // Standard routines stolen from MWTESample.c
- void AlertUser( short error );
- void EventLoop( void );
- void DoEvent( EventRecord *event );
- void AdjustCursor( Point mouse, RgnHandle region );
- void GetGlobalMouse( Point *mouse );
- void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
- void DoUpdate( WindowPtr window );
- void DoActivate( WindowPtr window, Boolean becomingActive );
- unsigned long GetSleep( void );
- void DoIdle( void );
- void DrawWindow( WindowPtr window );
- void AdjustMenus( void );
- void DoMenuCommand( long menuResult );
- void New_Window(void);
- Boolean DoCloseWindow( WindowPtr window );
- void Terminate( void );
- void Initialize( void );
- void BigBadError( short error );
- void GetTERect( WindowPtr window, Rect *teRect );
- void AdjustViewRect( TEHandle docTE );
- void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
- Boolean canRedraw );
- pascal void PascalClikLoop(void);
- pascal ProcPtr GetOldClikLoop(void);
- Boolean IsAppWindow( WindowPtr window );
- Boolean IsDAWindow( WindowPtr window );
- Boolean TrapAvailable( short tNumber, TrapType tType );
-
- // Generic symbiotic functions
- extern pascal OSErr HandleHeartBeat(AppleEvent *msg,AppleEvent *reply,long refcon);
- extern pascal OSErr HandleQuit(AppleEvent *msg,AppleEvent *reply,long refcon);
- extern pascal Boolean snd_version(void);
- extern void chk_heartbeat(void);
- extern void snd_heartbeat(void);
- extern void snd_quit(void);
- extern void snd_null(void);
-
- // External functions specific to this symbiont
- void new_connection(void);
- void InstallAppleEventHandlers(void);
-
-
- /* Define HiWrd and LoWrd macros for efficiency. */
- #define HiWrd(aLong) (((aLong) >> 16) & 0xFFFF)
- #define LoWrd(aLong) ((aLong) & 0xFFFF)
-
- /* Define TopLeft and BotRight macros for convenience. Notice the implicit
- dependency on the ordering of fields within a Rect */
- #define TopLeft(aRect) (* (Point *) &(aRect).top)
- #define BotRight(aRect) (* (Point *) &(aRect).bottom)
-
-
- /* This routine is part of the MPW runtime library. This external
- reference to it is done so that we can unload its segment, %A5Init. */
-
- //MW added void argument
- extern void _DataInit(void);
-
- /* A reference to our assembly language routine that gets attached to the clikLoop
- field of our TE record. */
-
-
- //MW added void argument.
- pascal void AsmClikLoop(void);
-
- //MW added the MPW assembly function in a C function.
- asm pascal void AsmClikLoop(void)
- {
- MOVEM.L D1-D2/A1,-(SP) // D0 and A0 need not be saved
- CLR.L -(SP) // make space for procedure pointer
- JSR GetOldClikLoop // get the old clikLoop
- MOVEA.L (SP)+,A0 // into A0
- MOVEM.L (SP)+,D1-D2/A1 // restore the world as it was
-
- JSR (A0) // and execute old clikLoop
-
- MOVEM.L D1-D2/A1,-(SP) // D0 and A0 need not be saved
- JSR PascalClikLoop // do our clikLoop
- MOVEM.L (SP)+,D1-D2/A1 // restore the world as it was
- MOVEQ #1,D0 // clear the zero flag so TextEdit keeps going
- RTS
- }
-
- #pragma segment Main
- //MW added void return-type and argument
- void main(void)
- {
- UnloadSeg((Ptr) _DataInit); /* note that _DataInit must not be in Main! */
-
- /* 1.01 - call to ForceEnvirons removed */
-
- /* If you have stack requirements that differ from the default,
- then you could use SetApplLimit to increase StackSpace at
- this point, before calling MaxApplZone. */
- MaxApplZone(); /* expand the heap so code segments load at the top */
-
- Initialize(); /* initialize the program */
- UnloadSeg((Ptr) Initialize); /* note that Initialize must not be in Main! */
-
- (void)InstallAppleEventHandlers(); // Install the AppleEvent handler functions
-
- (void)new_connection(); // Bring up PPC Browser for initial connection
-
- EventLoop(); /* call the main event loop */
- }
-
-
- /* Get events forever, and handle them by calling DoEvent.
- Also call AdjustCursor each time through the loop. */
-
- #pragma segment Main
- //MW added void argument
- void EventLoop(void)
- {
- RgnHandle cursorRgn;
- Boolean gotEvent;
- EventRecord event;
- Point mouse;
-
- cursorRgn = NewRgn(); /* we’ll pass WNE an empty region the 1st time thru */
- do {
- if ( gHasWaitNextEvent ) { /* use WNE if it is available */
- GetGlobalMouse(&mouse);
- AdjustCursor(mouse, cursorRgn);
- gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
- }
- else {
- SystemTask();
- gotEvent = GetNextEvent(everyEvent, &event);
- }
- if ( gotEvent ) {
- /* make sure we have the right cursor before handling the event */
- AdjustCursor(event.where, cursorRgn);
- DoEvent(&event);
- }
- else
- DoIdle(); /* perform idle tasks when it’s not our event */
- /* If you are using modeless dialogs that have editText items,
- you will want to call IsDialogEvent to give the caret a chance
- to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
- for a non-NIL value before calling IsDialogEvent. */
- } while ( true ); /* loop forever; we quit via ExitToShell */
- } /*EventLoop*/
-
-
- /* Do the right thing for an event. Determine what kind of event it is, and call
- the appropriate routines. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void DoEvent(EventRecord *event)
- {
- short part, err;
- WindowPtr window;
- char key;
- Point aPoint;
-
- switch ( event->what ) {
- case kHighLevelEvent:
- AEProcessAppleEvent(event);
- break;
- case nullEvent:
- /* we idle for null/mouse moved events ands for events which aren’t
- ours (see EventLoop) */
- DoIdle();
- break;
- case mouseDown:
- part = FindWindow(event->where, &window);
- switch ( part ) {
- case inMenuBar: /* process a mouse menu command (if any) */
- AdjustMenus(); /* bring ’em up-to-date */
- DoMenuCommand(MenuSelect(event->where));
- break;
- case inSysWindow: /* let the system handle the mouseDown */
- SystemClick(event, window);
- break;
- case inContent:
- if ( window != FrontWindow() ) {
- SelectWindow(window);
- /*DoEvent(event);*/ /* use this line for "do first click" */
- }
- break;
- case inDrag: /* pass screenBits.bounds to get all gDevices */
- DragWindow(window, event->where, &qd.screenBits.bounds);
- break;
- case inGoAway:
- if ( TrackGoAway(window, event->where) )
- DoCloseWindow(window); /* we don’t care if the user cancelled */
- break;
- }
- break;
- case keyDown:
- case autoKey: /* check for menukey equivalents */
- key = event->message & charCodeMask;
- if ( event->modifiers & cmdKey ) { /* Command key down */
- if ( event->what == keyDown ) {
- AdjustMenus(); /* enable/disable/check menu items properly */
- DoMenuCommand(MenuKey(key));
- }
- }
- break;
- case activateEvt:
- DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
- break;
- case updateEvt:
- // DoUpdate((WindowPtr) event->message);
- break;
- /* 1.01 - It is not a bad idea to at least call DIBadMount in response
- to a diskEvt, so that the user can format a floppy. */
- case diskEvt:
- if ( HiWord(event->message) != noErr ) {
- SetPt(&aPoint, kDILeft, kDITop);
- err = DIBadMount(aPoint, event->message);
- }
- break;
- case kOSEvent:
- /* 1.02 - must BitAND with 0x0FF to get only low byte */
- switch ((event->message >> 24) & 0x0FF) { /* high byte of message */
- case kMouseMovedMessage:
- DoIdle(); /* mouse-moved is also an idle event */
- break;
- case kSuspendResumeMessage: /* suspend/resume is also an activate/deactivate */
- gInBackground = (event->message & kResumeMask) == 0;
- DoActivate(FrontWindow(), !gInBackground);
- break;
- }
- break;
- }
- } /*DoEvent*/
-
-
- /* Change the cursor's shape, depending on its position. This also calculates the region
- where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
- this region, an event is generated. If there is more to the event than just
- “the mouse moved”, we get called before the event is processed to make sure
- the cursor is the right one. In any (ahem) event, this is called again before we
- fall back into WNE. */
-
- #pragma segment Main
- //MW Changed prototype style to new C
- void AdjustCursor(Point mouse,RgnHandle region)
- {
- WindowPtr window;
- RgnHandle arrowRgn;
- RgnHandle iBeamRgn;
- Rect iBeamRect;
-
- window = FrontWindow(); /* we only adjust the cursor when we are in front */
- if ( (! gInBackground) && (! IsDAWindow(window)) ) {
- /* calculate regions for different cursor shapes */
- arrowRgn = NewRgn();
- iBeamRgn = NewRgn();
-
- /* start arrowRgn wide open */
- SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
-
- /* calculate iBeamRgn */
- if ( IsAppWindow(window) ) {
- iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
- SetPort(window); /* make a global version of the viewRect */
- LocalToGlobal(&TopLeft(iBeamRect));
- LocalToGlobal(&BotRight(iBeamRect));
- RectRgn(iBeamRgn, &iBeamRect);
- /* we temporarily change the port’s origin to “globalfy” the visRgn */
- SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
- SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
- SetOrigin(0, 0);
- }
-
- /* subtract other regions from arrowRgn */
- DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
-
- /* change the cursor and the region parameter */
- if ( PtInRgn(mouse, iBeamRgn) ) {
- SetCursor(*GetCursor(iBeamCursor));
- CopyRgn(iBeamRgn, region);
- } else {
- SetCursor(&qd.arrow);
- CopyRgn(arrowRgn, region);
- }
-
- DisposeRgn(arrowRgn);
- DisposeRgn(iBeamRgn);
- }
- } /*AdjustCursor*/
-
-
- /* Get the global coordinates of the mouse. When you call OSEventAvail
- it will return either a pending event or a null event. In either case,
- the where field of the event record will contain the current position
- of the mouse in global coordinates and the modifiers field will reflect
- the current state of the modifiers. Another way to get the global
- coordinates is to call GetMouse and LocalToGlobal, but that requires
- being sure that thePort is set to a valid port. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void GetGlobalMouse(Point *mouse)
- {
- EventRecord event;
-
- OSEventAvail(kNoEvents, &event); /* we aren't interested in any events */
- *mouse = event.where; /* just the mouse position */
- } /*GetGlobalMouse*/
-
-
- /* Returns the update region in local coordinates */
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void GetLocalUpdateRgn(WindowPtr window,RgnHandle localRgn)
- {
- CopyRgn(((WindowPeek) window)->updateRgn, localRgn); /* save old update region */
- OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
- } /* GetLocalUpdateRgn */
-
-
- /* This is called when an update event is received for a window.
- It calls DrawWindow to draw the contents of an application window.
- As an efficiency measure that does not have to be followed, it
- calls the drawing routine only if the visRgn is non-empty. This
- will handle situations where calculations for drawing or drawing
- itself is very time-consuming. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void DoUpdate(WindowPtr window)
- {
- if ( IsAppWindow(window) ) {
- BeginUpdate(window); /* this sets up the visRgn */
- if ( ! EmptyRgn(window->visRgn) ) /* draw if updating needs to be done */
- DrawWindow(window);
- EndUpdate(window);
- }
- } /*DoUpdate*/
-
-
- /* This is called when a window is activated or deactivated.
- It calls TextEdit to deal with the selection. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void DoActivate(WindowPtr window, Boolean becomingActive)
- {
- RgnHandle tempRgn, clipRgn;
- DocumentPeek doc;
-
- if ( IsAppWindow(window) ) {
- doc = (DocumentPeek) window;
- if ( becomingActive ) {
- /* since we don’t want TEActivate to draw a selection in an area where
- we’re going to erase and redraw, we’ll clip out the update region
- before calling it. */
- tempRgn = NewRgn();
- clipRgn = NewRgn();
- GetLocalUpdateRgn(window, tempRgn); /* get localized update region */
- GetClip(clipRgn);
- DiffRgn(clipRgn, tempRgn, tempRgn); /* subtract updateRgn from clipRgn */
- SetClip(tempRgn);
- TEActivate(doc->docTE);
- SetClip(clipRgn); /* restore the full-blown clipRgn */
- DisposeRgn(tempRgn);
- DisposeRgn(clipRgn);
-
- }
- else {
- TEDeactivate(doc->docTE);
- /* the controls must be hidden on deactivation: */
- }
- }
- } /*DoActivate*/
-
-
- /* Calculate a sleep value for WaitNextEvent. This takes into account the things
- that DoIdle does with idle time. */
-
- #pragma segment Main
- //MW Added argument type (void)
- unsigned long GetSleep(void)
- {
- long sleep;
- WindowPtr window;
- TEHandle te;
-
- // MW MAXLONG was previously defined in values.h but Apple tells users to now use
- // MW the constants defined in the ANSI headers
- // sleep = MAXLONG; /* default value for sleep */
- sleep = 2147483647; /* default value for sleep */
- if ( !gInBackground ) {
- window = FrontWindow(); /* and the front window is ours... */
- if ( IsAppWindow(window) ) {
- te = ((DocumentPeek) (window))->docTE; /* and the selection is an insertion point... */
- if ( (*te)->selStart == (*te)->selEnd )
- sleep = GetCaretTime(); /* blink time for the insertion point */
- }
- }
- return sleep;
- } /*GetSleep*/
-
-
-
- /* This is called whenever we get a null event et al.
- It takes care of necessary periodic actions. For this program, it calls TEIdle. */
-
- #pragma segment Main
- //MW Added argument type (void).
- void DoIdle(void)
- {
- WindowPtr window;
-
- window = FrontWindow();
- if ( IsAppWindow(window) ) {
- TEIdle(((DocumentPeek) window)->docTE);
- if (TickCount() - time_of_last_send >= HEARTBEAT_SEND) snd_heartbeat();
- if (TickCount() - time_of_last_check >= HEARTBEAT_CHECK) chk_heartbeat();
- if (TimeToQuit == true) Terminate();
- }
- } /*DoIdle*/
-
-
- /* Draw the contents of an application window. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void DrawWindow(WindowPtr window)
- {
- SetPort(window);
- EraseRect(&window->portRect);
- DrawControls(window);
- DrawGrowIcon(window);
- TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
- } /*DrawWindow*/
-
-
- /* Enable and disable menus based on the current state.
- The user can only select enabled menu items. We set up all the menu items
- before calling MenuSelect or MenuKey, since these are the only times that
- a menu item can be selected. Note that MenuSelect is also the only time
- the user will see menu items. This approach to deciding what enable/
- disable state a menu item has the advantage of concentrating all
- the decision-making in one routine, as opposed to being spread throughout
- the application. Other application designs may take a different approach
- that may or may not be as valid. */
-
- #pragma segment Main
- //MW Added argument type (void).
- void AdjustMenus(void)
- {
- WindowPtr window;
- MenuHandle menu;
- long offset;
- Boolean undo;
- Boolean cutCopyClear;
- Boolean paste;
- TEHandle te;
-
- window = FrontWindow();
-
- menu = GetMHandle(mFile);
- if ( gNumDocuments < kMaxOpenDocuments )
- EnableItem(menu, iNew); /* New is enabled when we can open more documents */
- else
- DisableItem(menu, iNew);
-
- menu = GetMHandle(mEdit);
- undo = false;
- cutCopyClear = false;
- paste = false;
- if ( IsDAWindow(window) ) {
- undo = true; /* all editing is enabled for DA windows */
- cutCopyClear = true;
- paste = true;
- } else if ( IsAppWindow(window) ) {
- te = ((DocumentPeek) window)->docTE;
- if ( (*te)->selStart < (*te)->selEnd )
- cutCopyClear = false;
- /* Cut, Copy, and Clear is enabled for app. windows with selections */
- if ( GetScrap(nil, 'TEXT', &offset) > 0)
- paste = false; /* if there’s any text in the clipboard, paste is enabled */
- }
- if ( undo )
- EnableItem(menu, iUndo);
- else
- DisableItem(menu, iUndo);
- if ( cutCopyClear ) {
- EnableItem(menu, iCut);
- EnableItem(menu, iCopy);
- EnableItem(menu, iClear);
- } else {
- DisableItem(menu, iCut);
- DisableItem(menu, iCopy);
- DisableItem(menu, iClear);
- }
- if ( paste )
- EnableItem(menu, iPaste);
- else
- DisableItem(menu, iPaste);
- } /*AdjustMenus*/
-
-
- /* This is called when an item is chosen from the menu bar (after calling
- MenuSelect or MenuKey). It does the right thing for each command. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void DoMenuCommand(long menuResult)
- {
- short menuID, menuItem;
- short itemHit, daRefNum;
- Str255 daName;
- WindowPtr window;
-
- window = FrontWindow();
- menuID = HiWord(menuResult); /* use macros for efficiency to... */
- menuItem = LoWord(menuResult); /* get menu item number and menu number */
- switch ( menuID ) {
- case mApple:
- switch ( menuItem ) {
- case iAbout: /* bring up alert for About */
- itemHit = Alert(rAboutAlert, nil);
- break;
- default: /* all non-About items in this menu are DAs et al */
- /* type Str255 is an array in MPW 3 */
- GetItem(GetMHandle(mApple), menuItem, daName);
- daRefNum = OpenDeskAcc(daName);
- break;
- }
- break;
- case mFile:
- switch ( menuItem ) {
- case iNew:
- new_connection();
- break;
- case iQuit:
- Terminate();
- break;
- }
- break;
- }
- HiliteMenu(0); /* unhighlight what MenuSelect (or MenuKey) hilited */
- } /*DoMenuCommand*/
-
-
- // Create a new document and window.
- //
- #pragma segment Main
- void New_Window(void)
- {
- Boolean good;
- Ptr storage;
- WindowPtr window;
- Rect destRect, viewRect;
- DocumentPeek doc;
-
- extern Str255 hostname;
-
-
- storage = NewPtr(sizeof(DocumentRecord));
- if ( storage != nil ) {
- window = GetNewWindow(rJavWindow, storage, (WindowPtr) -1);
- SetWTitle(window,hostname);
- if ( window != nil ) {
- gNumDocuments += 1; /* this will be decremented when we call DoCloseWindow */
- good = false;
- SetPort(window);
- doc = (DocumentPeek) window;
- GetTERect(window, &viewRect);
- destRect = viewRect;
- destRect.right = destRect.left + kMaxDocWidth;
- doc->docTE = TENew(&destRect, &viewRect);
- good = doc->docTE != nil; /* if TENew succeeded, we have a good document */
- if ( good ) { /* 1.02 - good document? — proceed */
- // AdjustViewRect(doc->docTE);
- TEAutoView(true, doc->docTE);
- // MW Changed to conform to SDK 7 headers
- // doc->docClik = (ProcPtr) (*doc->docTE)->clikLoop;
- // (*doc->docTE)->clikLoop = (ClikLoopUPP) AsmClikLoop;
- doc->docClik = (ProcPtr) (*doc->docTE)->clickLoop;
- (*doc->docTE)->clickLoop = (TEClickLoopUPP) AsmClikLoop;
- }
-
- if ( good ) { /* good? — draw the window */
- ShowWindow(window);
- } else {
- DoCloseWindow(window); /* otherwise regret we ever created it... */
- AlertUser(eNoWindow); /* and tell user */
- }
- } else
- DisposPtr(storage); /* get rid of the storage if it is never used */
- }
- } /*New_Window*/
-
-
- /* Close a window. This handles desk accessory and application windows. */
-
- /* 1.01 - At this point, if there was a document associated with a
- window, you could do any document saving processing if it is 'dirty'.
- DoCloseWindow would return true if the window actually closed, i.e.,
- the user didn’t cancel from a save dialog. This result is handy when
- the user quits an application, but then cancels the save of a document
- associated with a window. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- Boolean DoCloseWindow(WindowPtr window)
- {
- TEHandle te;
-
- if ( IsDAWindow(window) )
- CloseDeskAcc(((WindowPeek) window)->windowKind);
- else if ( IsAppWindow(window) ) {
- te = ((DocumentPeek) window)->docTE;
- if ( te != nil )
- TEDispose(te); /* dispose the TEHandle if we got far enough to make one */
- /* 1.01 - We used to call DisposeWindow, but that was technically
- incorrect, even though we allocated storage for the window on
- the heap. We should instead call CloseWindow to have the structures
- taken care of and then dispose of the storage ourselves. */
- CloseWindow(window);
- DisposPtr((Ptr) window);
- gNumDocuments -= 1;
- }
- return true;
- } /*DoCloseWindow*/
-
-
- /**************************************************************************************
- *** 1.01 DoCloseBehind(window) was removed ***
-
- 1.01 - DoCloseBehind was a good idea for closing windows when quitting
- and not having to worry about updating the windows, but it suffered
- from a fatal flaw. If a desk accessory owned two windows, it would
- close both those windows when CloseDeskAcc was called. When DoCloseBehind
- got around to calling DoCloseWindow for that other window that was already
- closed, things would go very poorly. Another option would be to have a
- procedure, GetRearWindow, that would go through the window list and return
- the last window. Instead, we decided to present the standard approach
- of getting and closing FrontWindow until FrontWindow returns NIL. This
- has a potential benefit in that the window whose document needs to be saved
- may be visible since it is the front window, therefore decreasing the
- chance of user confusion. For aesthetic reasons, the windows in the
- application should be checked for updates periodically and have the
- updates serviced.
- **************************************************************************************/
-
-
- /* Clean up the application and exit. We close all of the windows so that
- they can update their documents, if any. */
-
- /* 1.01 - If we find out that a cancel has occurred, we won't exit to the
- shell, but will return instead. */
-
- #pragma segment Main
- //MW Added argument type (void).
- void Terminate(void)
- {
- WindowPtr aWindow;
- Boolean closed;
-
- closed = true;
- do {
- aWindow = FrontWindow(); /* get the current front window */
- if (aWindow != nil)
- closed = DoCloseWindow(aWindow); /* close this window */
- }
- while (closed && (aWindow != nil));
- if (closed) {
- snd_quit();
- ExitToShell();
- } /* exit if no cancellation */
- } /*Terminate*/
-
-
- /* Set up the whole world, including global variables, Toolbox managers,
- menus, and a single blank document. */
-
- /* 1.01 - The code that used to be part of ForceEnvirons has been moved into
- this module. If an error is detected, instead of merely doing an ExitToShell,
- which leaves the user without much to go on, we call AlertUser, which puts
- up a simple alert that just says an error occurred and then calls ExitToShell.
- Since there is no other cleanup needed at this point if an error is detected,
- this form of error- handling is acceptable. If more sophisticated error recovery
- is needed, an exception mechanism, such as is provided by Signals, can be used. */
-
- #pragma segment Initialize
- //MW Added argument type (void).
- void Initialize(void)
- {
- Handle menuBar;
- long total, contig;
- EventRecord event;
- short count;
-
- gInBackground = false;
-
- InitGraf((Ptr) &qd.thePort);
- InitFonts();
- InitWindows();
- InitMenus();
- TEInit();
- InitDialogs(nil);
- InitCursor();
-
- /* Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
- if you are using it. */
- /* NOTE -- It is no longer necessary, and actually unhealthy, to check
- PortBUse and SPConfig before opening AppleTalk. The drivers are capable
- of checking for port availability themselves. */
-
- /* This next bit of code is necessary to allow the default button of our
- alert be outlined.
- 1.02 - Changed to call EventAvail so that we don't lose some important
- events. */
-
- for (count = 1; count <= 3; count++)
- EventAvail(everyEvent, &event);
-
- /* Ignore the error returned from SysEnvirons; even if an error occurred,
- the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
- call to SysEnvirons by calling it after initializing AppleTalk. */
-
- SysEnvirons(kSysEnvironsVersion, &gMac);
-
- /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
-
- if (gMac.machineType < 0) BigBadError(eWrongMachine);
-
- /* 1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
- in TrapAvailable if a tool trap value is out of range. */
-
- gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
-
- /* 1.01 - We used to make a check for memory at this point by examining ApplLimit,
- ApplicZone, and StackSpace and comparing that to the minimum size we told
- MultiFinder we needed. This did not work well because it assumed too much about
- the relationship between what we asked MultiFinder for and what we would actually
- get back, as well as how to measure it. Instead, we will use an alternate
- method comprised of two steps. */
-
- /* It is better to first check the size of the application heap against a value
- that you have determined is the smallest heap the application can reasonably
- work in. This number should be derived by examining the size of the heap that
- is actually provided by MultiFinder when the minimum size requested is used.
- The derivation of the minimum size requested from MultiFinder is described
- in Sample.h. The check should be made because the preferred size can end up
- being set smaller than the minimum size by the user. This extra check acts to
- insure that your application is starting from a solid memory foundation. */
-
- if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) BigBadError(eSmallSize);
-
- /* Next, make sure that enough memory is free for your application to run. It
- is possible for a situation to arise where the heap may have been of required
- size, but a large scrap was loaded which left too little memory. To check for
- this, call PurgeSpace and compare the result with a value that you have determined
- is the minimum amount of free memory your application needs at initialization.
- This number can be derived several different ways. One way that is fairly
- straightforward is to run the application in the minimum size configuration
- as described previously. Call PurgeSpace at initialization and examine the value
- returned. However, you should make sure that this result is not being modified
- by the scrap's presence. You can do that by calling ZeroScrap before calling
- PurgeSpace. Make sure to remove that call before shipping, though. */
-
- /* ZeroScrap(); */
-
- PurgeSpace(&total, &contig);
- if (total < kMinSpace)
- if (UnloadScrap() != noErr)
- BigBadError(eNoMemory);
- else {
- PurgeSpace(&total, &contig);
- if (total < kMinSpace)
- BigBadError(eNoMemory);
- }
-
- /* The extra benefit to waiting until after the Toolbox Managers have been initialized
- to check memory is that we can now give the user an alert to tell him/her what
- happened. Although it is possible that the memory situation could be worsened by
- displaying an alert, MultiFinder would gracefully exit the application with
- an informative alert if memory became critical. Here we are acting more
- in a preventative manner to avoid future disaster from low-memory problems. */
-
- menuBar = GetNewMBar(rMenuBar); /* read menus into menu bar */
- if ( menuBar == nil )
- BigBadError(eNoMemory);
- SetMenuBar(menuBar); /* install menus */
- DisposHandle(menuBar);
- AddResMenu(GetMHandle(mApple), 'DRVR'); /* add DA names to Apple menu */
- DrawMenuBar();
-
- gNumDocuments = 0;
-
- /* do other initialization here */
-
- } /*Initialize*/
-
-
- /* Used whenever a, like, fully fatal error happens */
- #pragma segment Initialize
- //MW Changed prototype style to new C (old C to new C)
- void BigBadError(short error)
- {
- AlertUser(error);
- ExitToShell();
- }
-
-
- /* Return a rectangle that is inset from the portRect by the size of
- the scrollbars and a little extra margin. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void GetTERect(WindowPtr window,Rect *teRect)
- {
- *teRect = window->portRect;
- InsetRect(teRect, 0, 5); /* adjust for margin */
- } /*GetTERect*/
-
-
- /* Update the TERec's view rect so that it is the greatest multiple of
- the lineHeight that still fits in the old viewRect. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void AdjustViewRect(TEHandle docTE)
- {
- TEPtr te;
-
- te = *docTE;
- te->viewRect.bottom = (((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
- * te->lineHeight) + te->viewRect.top;
- } /*AdjustViewRect*/
-
-
- #pragma segment Main
- Boolean needsResize;
- //MW Added argument type (void).
- pascal void PascalClikLoop(void)
- {
- WindowPtr window;
- RgnHandle region;
-
- window = FrontWindow();
- region = NewRgn();
- GetClip(region); /* save clip */
- ClipRect(&window->portRect);
- SetClip(region); /* restore clip */
- DisposeRgn(region);
- } /* Pascal/C ClikLoop */
-
-
- /* Gets called from our assembly language routine, AsmClikLoop, which is in
- turn called by the TEClick toolbox routine. It returns the address of the
- default clikLoop routine that was put into the TERec by TEAutoView to
- AsmClikLoop so that it can call it. */
-
- #pragma segment Main
- //MW Added argument type.
- pascal ProcPtr GetOldClikLoop(void)
- {
- return ((DocumentPeek)FrontWindow())->docClik;
- } /* GetOldClikLoop */
-
-
- /* Check to see if a window belongs to the application. If the window pointer
- passed was NIL, then it could not be an application window. WindowKinds
- that are negative belong to the system and windowKinds less than userKind
- are reserved by Apple except for windowKinds equal to dialogKind, which
- mean it is a dialog.
- 1.02 - In order to reduce the chance of accidentally treating some window
- as an AppWindow that shouldn't be, we'll only return true if the windowkind
- is userKind. If you add different kinds of windows to Sample you'll need
- to change how this all works. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- Boolean IsAppWindow(WindowPtr window)
- {
- short windowKind;
-
- if ( window == nil )
- return false;
- else { /* application windows have windowKinds = userKind (8) */
- windowKind = ((WindowPeek) window)->windowKind;
- return (windowKind == userKind);
- }
- } /*IsAppWindow*/
-
-
- /* Check to see if a window belongs to a desk accessory. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- Boolean IsDAWindow(WindowPtr window)
- {
- if ( window == nil )
- return false;
- else /* DA windows have negative windowKinds */
- return ((WindowPeek) window)->windowKind < 0;
- } /*IsDAWindow*/
-
-
- /* Check to see if a given trap is implemented. This is only used by the
- Initialize routine in this program, so we put it in the Initialize segment.
- The recommended approach to see if a trap is implemented is to see if
- the address of the trap routine is the same as the address of the
- Unimplemented trap. */
- /* 1.02 - Needs to be called after call to SysEnvirons so that it can check
- if a ToolTrap is out of range of a pre-MacII ROM. */
-
- #pragma segment Initialize
- //MW Changed prototype style to new C (old C to new C)
- Boolean TrapAvailable(short tNumber,TrapType tType)
- {
- if ( ( tType == (unsigned char) ToolTrap ) &&
- ( gMac.machineType > envMachUnknown ) &&
- ( gMac.machineType < envMacII ) ) { /* it's a 512KE, Plus, or SE */
- tNumber = tNumber & 0x03FF;
- if ( tNumber > 0x01FF ) /* which means the tool traps */
- tNumber = _Unimplemented; /* only go to 0x01FF */
- }
- return NGetTrapAddress(tNumber, tType) != GetToolTrapAddress(_Unimplemented);
- // MW return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
- } /*TrapAvailable*/
-
-
- /* Display an alert that tells the user an error occurred, then exit the program.
- This routine is used as an ultimate bail-out for serious errors that prohibit
- the continuation of the application. Errors that do not require the termination
- of the application should be handled in a different manner. Error checking and
- reporting has a place even in the simplest application. The error number is used
- to index an 'STR#' resource so that a relevant message can be displayed. */
-
- #pragma segment Main
- //MW Changed prototype style to new C (old C to new C)
- void AlertUser(short error)
- {
- short itemHit;
- Str255 message;
-
- SetCursor(&qd.arrow);
- /* type Str255 is an array in MPW 3 */
- GetIndString(message, kErrStrings, error);
- //MW changed "" for "\p"
- ParamText(message, "\p", "\p", "\p");
- itemHit = Alert(rUserAlert, nil);
- } /* AlertUser */
-
-
- // Handle an incoming HeartBeat AppleEvent.
- //
- extern pascal OSErr HandleHeartBeat(AppleEvent *msg,AppleEvent *reply,long refcon)
- {
-
- time_of_last_recv = TickCount();
- return (noErr);
- } // HandleHeartBeat()
-
-
- // Handle and incoming Quit AppleEvent.
- //
- extern pascal OSErr HandleQuit(AppleEvent *msg,AppleEvent *reply,long refcon)
- {
-
- TimeToQuit=TRUE; // Time to die...
- return (noErr);
- } // HandleQuit()
-
-
- // Send out version string to the server symbiont via an AppleEvent.
- //
- extern pascal Boolean snd_version(void)
- {
- char status;
- char theVersion[10];
- AppleEvent theAppleEvent;
- AppleEvent reply;
- AESendMode sendMode;
- AESendPriority sendPriority;
- AEAddressDesc target;
- DescType returnedType;
- Size returnedSize;
- long timeOutInTicks;
- int retval, result;
-
- BlockMove(VERSION,theVersion,5);
-
- retval=AECreateDesc(typeTargetID,&TheTarget,sizeof(TargetID),&target);
- retval=AECreateAppleEvent(kAEAUXSuite,kAEVersion,&target, kAutoGenerateReturnID,kAnyTransactionID,&theAppleEvent);
- retval=AEPutParamPtr(&theAppleEvent,keySessionID,typeInteger,&TheTarget.sessionID,sizeof(TheTarget.sessionID));
- retval=AEPutParamPtr(&theAppleEvent,keyAEJVersion,typeChar,theVersion,4);
- sendMode = kAEWaitReply;
- sendPriority = kAENormalPriority;
- timeOutInTicks = kAEDefaultTimeout;
- retval=AESend(&theAppleEvent,&reply,sendMode,sendPriority,timeOutInTicks,NULL,NULL);
- AEDisposeDesc(&target);
- AEDisposeDesc(&theAppleEvent);
- if (retval == noErr) {
- result = AEGetParamPtr(&reply,keyErrorNumber,typeChar,&returnedType,(Ptr)&status,sizeof(char),&returnedSize);
- result = AEGetParamPtr(&reply,keyErrorString,typeChar,&returnedType,(Ptr)theVersion,10,&returnedSize);
- theVersion[returnedSize]='\0';
- if (status == 'F') {
- AlertUser(eVersion);
- return FALSE;
- }
- else
- BlockMove(theVersion,&ServerOSVer,returnedSize);
- }
- else {
- AlertUser(eAESend);
- return FALSE;
- }
- return TRUE;
- } // snd_version()
-
-
- // Check to see if we have received a HeartBeat AppleEvent since last check.
- //
- void chk_heartbeat(void)
- {
- time_of_last_check = TickCount();
- if ((time_of_last_check - time_of_last_recv) > HEARTBEAT_CHECK) {
- missed_heartbeats++;
- if (missed_heartbeats >= MAX_MISSED_HEARTBEATS) {
- TimeToQuit=TRUE;
- }
- }
- else
- missed_heartbeats = 0;
- } // chk_heartheat()
-
-
-
- // Send a HeartBeat AppleEvent to the server symbiont.
- //
- extern void snd_heartbeat(void)
- {
- AppleEvent theAppleEvent;
- AppleEvent reply;
- AESendMode sendMode;
- AESendPriority sendPriority;
- AEAddressDesc target;
- long timeOutInTicks;
- int retval;
-
- time_of_last_send=TickCount();
- retval=AECreateDesc(typeTargetID,&TheTarget,sizeof(TargetID),&target);
- retval=AECreateAppleEvent(kAEAUXSuite,kAEHeartBeat,&target, kAutoGenerateReturnID,kAnyTransactionID,&theAppleEvent);
- retval=AEPutParamPtr(&theAppleEvent,keySessionID,typeInteger,&TheTarget.sessionID,sizeof(TheTarget.sessionID));
- sendMode = kAENoReply;
- sendPriority = kAENormalPriority;
- timeOutInTicks = kAEDefaultTimeout;
- retval=AESend(&theAppleEvent,&reply,sendMode,sendPriority,timeOutInTicks,NULL,NULL);
- AEDisposeDesc(&target);
- AEDisposeDesc(&theAppleEvent);
- } // snd_heartbeat()
-
-
- // Send a QUIT AppleEvent to the server symbiont.
- //
- extern void snd_quit(void)
- {
- AppleEvent theAppleEvent;
- AppleEvent reply;
- AESendMode sendMode;
- AESendPriority sendPriority;
- AEAddressDesc target;
- long timeOutInTicks;
- int retval;
-
- retval=AECreateDesc(typeTargetID,&TheTarget,sizeof(TargetID),&target);
- retval=AECreateAppleEvent(kAEAUXSuite,kAEQuit,&target, kAutoGenerateReturnID,kAnyTransactionID,&theAppleEvent);
- retval=AEPutParamPtr(&theAppleEvent,keySessionID,typeInteger,&TheTarget.sessionID,sizeof(TheTarget.sessionID));
- sendMode = kAENoReply;
- sendPriority = kAENormalPriority;
- timeOutInTicks = kAEDefaultTimeout;
- retval=AESend(&theAppleEvent,&reply,sendMode,sendPriority,timeOutInTicks,NULL,NULL);
- AEDisposeDesc(&target);
- AEDisposeDesc(&theAppleEvent);
- } // snd_quit()
-
-
- // Send a NULL AppleEvent to the server symbiont.
- // NOTE: This is usually the first event sent to a server symbiont.
- // It has the effect of actually completing the connection and
- // causes a "StartSecureSession()" to be run automatically.
- //
- extern void snd_null(void)
- {
- AppleEvent theAppleEvent;
- AppleEvent reply;
- AESendMode sendMode;
- AESendPriority sendPriority;
- AEAddressDesc target;
- long timeOutInTicks;
- int retval;
-
- retval=AECreateDesc(typeTargetID,&TheTarget,sizeof(TheTarget), &target);
- retval=AECreateDesc(typeNull,NULL,0, &reply);
- retval=AECreateAppleEvent(kAEAUXSuite,kAENull, &target, kAutoGenerateReturnID,kAnyTransactionID,&theAppleEvent);
- retval=AEPutParamPtr(&theAppleEvent,keySessionID,typeInteger,&TheTarget.sessionID,sizeof(TheTarget.sessionID));
- sendMode = kAENoReply;
- sendPriority = kAENormalPriority;
- timeOutInTicks = kAEDefaultTimeout;
- retval=AESend(&theAppleEvent,&reply,sendMode,sendPriority,timeOutInTicks,NULL,NULL);
- AEDisposeDesc(&target);
- AEDisposeDesc(&theAppleEvent);
- } // snd_null()
-
-